<template>
  <div>
    <q-dialog maximized flat persistent ref="dialog">
      <q-form  class="dialog_card column">
        <h5 class="view_title justify-between q-px-md">
          ai提问
          <q-btn dense outline round icon="clear" size="sm" v-close-popup />
        </h5>
        <div class="chat-container">
          <div class="chat-messages">
            <div v-for="(message, index) in messages" :key="index" :class="{ 'self-message': message.self, 'other-message': !message.self }">
              <div class="message-avatar">
                <img :src="message.avatar" alt="Avatar" />
              </div>
              <div class="message-content">
                <div class="message-name">{{message.name }}</div>

                <div class="message-text" v-html="renderMarkdown(processedValue( message.text))"></div>
              </div>
            </div>
          </div>
          <div class="chat-input">
            <input v-model="inputText" placeholder="输入你的消息" @keydown.enter.prevent="sendMessage" />
            <button @click="sendMessage">发送</button>
          </div>
        </div>
      </q-form>
    </q-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import MarkdownIt from 'markdown-it';

export default {
  data() {
    return {
      imgUrl: `${process.env.BASE_URL}/sys/common/static`,
      // 存储用户输入的消息
      inputText: '',
      // 存储当前正在流式输出的消息
      currentStreamMessage: '',
      // 存储聊天消息的数组
      messages: [
        {
          avatar: 'https://cdn.quasar.dev/img/boy-avatar.png',
          name: 'AI',
          text: '欢迎使用聊天服务！有什么问题尽管问我。',
          self: false,
        },
      ],
    };
  },
  methods: {
     renderMarkdown(text) {
      const md = new MarkdownIt();
      return md.render(text);
    },
    imagePath(src) {
      let path = '';
      if (src) {
        if (src.startsWith('http')) {
          return src;
        }
        path = `${this.imgUrl}/${src}`;
      }
      return path;
    },
    async sendToAi(message){
      const headers = {
        'Content-Type': 'application/json',
        Authorization: localStorage.getItem('Authorization'),
      };
      try {
        // 发送请求到后台接口
        const response = await axios.get('http://localhost:9008/weather-api/deepSeek', {
          params: {
            message: message,
          },
          headers,
        });
        // 添加 AI 回复到消息列表
        this.messages.push({
          avatar: 'https://cdn.quasar.dev/img/boy-avatar.png',
          name: 'AI',
          text: response.data,
          self: false,
        });
        
      } catch (error) {
        console.error('请求出错:', error);
        // 添加错误提示到消息列表
        this.messages.push({
          avatar: 'https://cdn.quasar.dev/img/boy-avatar.png',
          name: 'AI',
          text: '抱歉，请求出错，请稍后再试。',
          self: false,
        });
      }
    },
    // 发送消息的函数
     sendMessage(event) {
      event.preventDefault();
      if (this.inputText.trim() === '') return;
      const path = this.imagePath(this.$store.state.User.info.avatar);
      // 添加用户消息到消息列表
      this.messages.push({
        avatar: path, // 使用 Vuex 中的头像信息
        name: '你',
        text: this.inputText,
        self: true,
      });
    this.sendToAi(this.inputText);
     
    
      // 清空输入框
      this.inputText = '';
    },
    processedValue( message) {
      let newValue = message.replace(/<think>([\s\S]*?)<\/think>/g, (_, content) => {
        const lines = content.trim().split('\n');
        const quotedLines = lines.map((line) => `> ${line}`).join('\n');
        return quotedLines;
      });
      return newValue;
    },
  },
  
};
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 90%;
  border: 1px solid #ccc;
  border-radius: 4px;
  padding: 16px;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  margin-bottom: 16px;
}

.message {
  display: flex;
  margin-bottom: 16px;
}

.self-message {
  justify-content: flex-end;
}

.other-message {
  justify-content: flex-start;
}

.message-avatar {
  width: 40px;
  height: 40px;
  margin-right: 8px;
}

.message-avatar img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
}

.message-content {
  background-color: #f0f0f0;
  padding: 8px;
  border-radius: 4px;
}

.message-name {
  font-weight: bold;
  margin-bottom: 4px;
}

.chat-input {
  display: flex;
}

.chat-input input {
  flex: 1;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
  margin-right: 8px;
}

.chat-input button {
  padding: 8px 16px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.chat-input button:hover {
  background-color: #0056b3;
}
</style>
